<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>个人设置</h3>
        </div>
      </template>

      <el-form :model="profileForm" :rules="rules" ref="profileFormRef" label-width="100px">
        <!-- 头像设置 -->
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
              accept="image/*"
            >
              <img v-if="profileForm.avatar" :src="getAvatarUrl(profileForm.avatar)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="avatar-tips">
              <p>点击上传头像</p>
              <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="profileForm.username" 
            placeholder="请输入用户名"
            :disabled="true"
          />
          <div class="form-tip">用户名不可修改</div>
        </el-form-item>

        <!-- 显示名称 -->
        <el-form-item label="显示名称" prop="displayName">
          <el-input 
            v-model="profileForm.displayName" 
            placeholder="请输入显示名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="profileForm.email" 
            placeholder="请输入邮箱地址"
            type="email"
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="profileForm.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="个人描述" prop="description">
          <el-input 
            v-model="profileForm.description" 
            type="textarea"
            :rows="4"
            placeholder="请输入个人描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存修改
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 密码修改卡片 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <h3>修改密码</h3>
        </div>
      </template>

      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="passwordForm.currentPassword" 
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handlePasswordSave" :loading="passwordSaving">
            修改密码
          </el-button>
          <el-button @click="handlePasswordReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getAdminProfile, updateAdminProfile, updateAdminPassword } from '@/api'

// 路由实例
const router = useRouter()

// 表单引用
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 加载状态
const saving = ref(false)
const passwordSaving = ref(false)

// 上传配置
const uploadUrl = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/admin/profile/avatar`
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
}

// 个人信息表单
const profileForm = reactive({
  username: 'admin',
  displayName: '管理员',
  email: '',
  phone: '',
  description: '',
  avatar: '/touxiang.png'
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isImage = rawFile.type.startsWith('image/')
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = async (response) => {
  if (response.success) {
    profileForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
    // 重新加载个人信息以确保头像URL是最新的
    await loadProfile()
    
    // 发出头像更新事件，通知布局组件刷新头像
    window.dispatchEvent(new CustomEvent('avatarUpdated', {
      detail: { avatarUrl: response.data.url }
    }))
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传失败
const handleAvatarError: UploadProps['onError'] = () => {
  ElMessage.error('头像上传失败，请重试')
}

// 获取头像完整URL
const getAvatarUrl = (avatarPath: string) => {
  if (!avatarPath || avatarPath === '/touxiang.png') {
    return '/touxiang.png'
  }
  
  // 如果已经是完整URL，直接返回
  if (avatarPath.startsWith('http://') || avatarPath.startsWith('https://')) {
    return avatarPath
  }
  
  // 如果是头像路径，使用API端点
  if (avatarPath.startsWith('/uploads/avatars/')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const filename = avatarPath.replace('/uploads/avatars/', '')
    return `${baseUrl}/api/admin/avatars/${filename}`
  }
  
  // 其他相对路径，加上API基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
  return baseUrl + avatarPath
}

// 加载个人信息
const loadProfile = async () => {
  try {
    const response = await getAdminProfile()
    if (response.success && response.data) {
      profileForm.username = response.data.username || 'admin'
      profileForm.displayName = response.data.nickname || '管理员'
      profileForm.email = response.data.email || ''
      profileForm.phone = response.data.phone || ''
      profileForm.description = response.data.description || ''
      profileForm.avatar = response.data.avatar || '/touxiang.png'
    }
  } catch (error) {
    console.error('加载个人信息失败:', error)
    ElMessage.error('加载个人信息失败')
  }
}

// 保存个人信息
const handleSave = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    saving.value = true

    const requestData = {
      displayName: profileForm.displayName,
      email: profileForm.email,
      phone: profileForm.phone,
      description: profileForm.description,
      avatar: profileForm.avatar
    }

    const response = await updateAdminProfile(requestData)
    if (response.success) {
      ElMessage.success('保存成功')
      // 重新加载个人信息
      await loadProfile()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 重置个人信息表单
const handleReset = () => {
  profileFormRef.value?.resetFields()
  loadProfile()
}

// 保存密码
const handlePasswordSave = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    
    await ElMessageBox.confirm('确定要修改密码吗？修改后需要重新登录。', '提示', {
      type: 'warning'
    })

    passwordSaving.value = true

    const requestData = {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    }

    const response = await updateAdminPassword(requestData)
    if (response.success) {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除token，跳转到登录页
      localStorage.removeItem('admin_token')
      await router.push('/login')
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败')
    }
  } finally {
    passwordSaving.value = false
  }
}

// 重置密码表单
const handlePasswordReset = () => {
  passwordFormRef.value?.resetFields()
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-card,
.password-card {
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.avatar-upload {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.avatar-tips {
  flex: 1;
}

.avatar-tips p {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #606266;
}

.avatar-tips p:last-child {
  font-size: 12px;
  color: #909399;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}
</style>
